<template>
  <div>
    <div id="container"></div>
    <div class="coordinates">
      当前坐标：{{ lng.toFixed(6) }}, {{ lat.toFixed(6) }}
    </div>
    <div class="search-container">
      <input v-model="searchText" placeholder="请输入地名" @keyup.enter="handleSearch" />
      <button @click="handleSearch">搜索</button>
    </div>
  </div>

</template>

<script>

import AMapLoader from '@amap/amap-jsapi-loader'

window._AMapSecurityConfig = {
  securityJsCode: 'e2ba8a5fa6754e1f60b36f3b79f2011c'
}
export default {
  name: "MapContainer",
  data() {
    return {
      map: null,
     /* lng: 101.725377,
      lat: 26.567969,*/
      lng: '',
      lat: '',
      marker: null,
      searchText: '',
    }
  },
  mounted() {
    this.initMap()
  },
  methods: {
    initMap() {
      let load = AMapLoader.load({
        key: "d3a325e82b58b05fbb8f6f76c9c96437",             // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Scale', 'AMap.Autocomplete', 'AMap.PlaceSearch',"AMap.Geocoder"],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        this.map = new AMap.Map("container", {  //设置地图容器id
          viewMode: "2D",    //是否为3D地图模式
          zoom: 16,           //初始化地图级别
          center: [this.lng, this.lat], //初始化地图中心点位置
          resizeEnable: true
        })
        this.map.addControl(new AMap.Scale())

        // 初始化标记
        this.addMarker(this.lng, this.lat)

        // 绑定点击事件
        this.map.on('click', (e) => {
          this.handleMapClick(e)
        })

        // 初始化自动完成和地点搜索
        this.initAutoComplete(AMap);
      }).catch(e => {
        console.log(e);
      })
     // console.log(load)
    },
    initAutoComplete(AMap) {
      const autoOptions = {
        city: '全国', // 城市，默认全国
        input: document.getElementById('searchText')
      };
      const autoComplete = new AMap.AutoComplete(autoOptions);
      const placeSearch = new AMap.PlaceSearch({
        map: this.map
      });

      AMap.event.addListener(autoComplete, 'select', (e) => {
        placeSearch.setCity(e.poi.adcode);
        placeSearch.search(e.poi.name);
      });
    },
    handleSearch() {
      if (!this.map) return;

      const searchText = this.searchText.trim();
      if (searchText) {
        const placeSearch = new AMap.PlaceSearch({
          map: this.map
        });
        placeSearch.search(searchText);
      }
    },

    handleMapClick(e) {
      //console.log("当前位置信息为：",e.lnglat.getLng())
      // 更新坐标
      this.lng = e.lnglat.getLng()
      this.lat = e.lnglat.getLat()
      // 更新标记位置
      this.updateMarker(e.lnglat)

    },

    addMarker(lng, lat) {
      if (this.marker) {
        this.marker.setMap(null)
      }

      this.marker = new AMap.Marker({
        position: [lng, lat],
        map: this.map,
        icon: new AMap.Icon({
          image: require('@/assets/flag/icon4.svg'),
          size: new AMap.Size(28, 38),
          imageSize: new AMap.Size(28, 38),
          // 添加 imageOffset 属性
        }),
        animation: "AMAP_ANIMATION_DROP",
      })
    },
    updateMarker(lnglat) {
      this.marker.setPosition(lnglat)
      this.map.setCenter(lnglat)
    },
  }

}
</script>

<style scoped>



.map-wrapper {
  position: relative;
  height: 100vh;
}
#container{
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 1100px;
}
.coordinates {
  position: absolute;
  top: 20px; /* 改为上方定位 */
  left: 50%;
  transform: translateX(-50%); /* 水平居中 */
  padding: 10px 20px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 25px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 999;
  font-size: 14px;
  color: #2c3e50;
  border: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  gap: 8px;
  backdrop-filter: blur(4px); /* 毛玻璃效果 */
}
.coordinates::before {
  content: '📍';
  font-size: 16px;
}
.search-container {
  position: absolute;
  top: 80px; /* 调整顶部距离 */
  left: 50%;
  transform: translateX(-50%);
  padding: 10px 20px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 25px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 999;
  font-size: 14px;
  color: #2c3e50;
  border: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  gap: 8px;
  backdrop-filter: blur(4px); /* 毛玻璃效果 */
}

.search-container input {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 200px;
}

.search-container button {
  padding: 8px 16px;
  border: none;
  background-color: #007bff;
  color: white;
  border-radius: 4px;
  cursor: pointer;
}

.search-container button:hover {
  background-color: #0056b3;
}
</style>


<!--
<template>
  <div>
    <el-button class="get-position" @click="openMapDialog">
      <el-icon class="el-icon-position" />
      获取位置
    </el-button>

    <el-dialog
        title="获取位置信息"
        :visible.sync="getLocationFlag"
        width="60%"
        @opened="handleMapReady"
        @closed="handleMapClose">
      <div class="map-container">
        <el-amap-search-box
            class="search-box"
            :search-option="searchOption"
            :on-search-result="onSearchResult"/>

        &lt;!&ndash; 地图容器核心结构 &ndash;&gt;
        <div class="amap-wrapper">
          <el-amap
              ref="amapInstance"
              :amap-manager="amapManager"
              :center="center"
              :zoom="zoom"
              :plugin="plugin"
              :events="events"
              :vid="'amapContainer' + Date.now()">

            &lt;!&ndash; 内置地图控件 &ndash;&gt;
            <el-amap-control-scale position="LB"/>
            <el-amap-control-tool-bar position="RT"/>
          </el-amap>
        </div>

        <div class="location-info">
          <div>
            <p>详细地址：{{ address }}</p>
            <p>经纬度坐标：{{ center.join(', ') }}</p>
          </div>
          <el-button
              type="success"
              size="mini"
              @click="handleClose">
            确认位置
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { AMapManager } from 'vue-amap'

export default {
  data() {
    return {
      getLocationFlag: false,
      amapManager: new AMapManager(),
      searchOption: { city: '', citylimit: false },
      center: [116.397428, 39.90923],  // 默认北京中心点
      zoom: 12,
      address: '',
      marker: null,
      plugin: [
        'ToolBar',
        {
          pName: 'Geolocation',
          events: {
            init: o => this.initGeolocation(o)
          }
        }
      ],
      events: {
        init: o => this.initMap(o),
        click: e => this.handleMapClick(e)
      }
    }
  },
  methods: {
    // 打开对话框时初始化
    openMapDialog() {
      this.getLocationFlag = true

    },

    /*// 地图初始化完成
    handleMapReady() {
      this.$nextTick(() => {
        const map = this.amapManager._map
        if (map) {
          map.resize()
          this.addDefaultMarker()
        }
      })
    },*/

    // 添加默认标记
    addDefaultMarker() {
      if (!this.marker && this.center) {
        this.marker = new AMap.Marker({
          position: this.center,
          map: this.amapManager._map
        })
      }
    },

    // 地图点击事件
    handleMapClick(e) {
      console.log('原始坐标对象:', e.lnglat)
      console.log('转换后坐标:', lng, lat)
      this.updatePosition(e.lnglat)
      this.reverseGeocode(e.lnglat)
    },

    // 更新坐标
    updatePosition(lnglat) {
      this.center = [lnglat.lng, lnglat.lat]
      if (this.marker) {
        this.marker.setPosition(lnglat)
      }
    },

    // 地理编码
    reverseGeocode(lnglat) {
      new AMap.Geocoder().getAddress(lnglat, (status, result) => {
        if (status === 'complete') {
          this.address = result.regeocode?.formattedAddress || '未知地址'
        } else {
          console.error('地理编码失败', result)
          this.address = '地址解析失败'
        }
      })
    },

    // 初始化定位功能
    initGeolocation(geolocation) {
      geolocation.getCurrentPosition((status, result) => {
        if (result?.position) {
          this.updatePosition(result.position)
          this.address = result.formattedAddress
        }
      })
    },

    // 搜索回调
    onSearchResult(pois) {
      if (pois?.length) {
        const { lng, lat, location } = pois[0]
        this.center = [lng, lat]
        this.updatePosition({ lng, lat })
      }
    },

    // 关闭处理
    handleClose() {
      this.$emit('location-selected', {
        address: this.address,
        lng: this.center[0],
        lat: this.center[1]
      })
      this.getLocationFlag = false
    },

    // 清理资源
    handleMapClose() {
      if (this.marker) {
        this.marker.setMap(null)
        this.marker = null
      }
    }
  },
  beforeDestroy() {
    if (this.amapManager._map) {
      this.amapManager._map.destroy()
    }
  }
}
</script>

<style scoped>
.map-container {
  position: relative;
  height: 60vh;
}

.amap-wrapper {
  height: 400px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.search-box {
  position: absolute;
  top: 15px;
  right: 15px;
  z-index: 999;
  width: 300px;
}

.location-info {
  margin-top: 15px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.get-position {
  margin: 10px 0;
}
</style>
-->


